package com.zxj.test.common.handler;

import java.util.ArrayList;
import java.util.List;

import com.zxj.test.common.api.Response;
import com.zxj.test.common.exception.AbstractException;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author zxj
 * @date 2020/7/18
 */
@RestControllerAdvice
public class BaseExceptionHandler {

    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    public Response<Void> handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<String> messageList = new ArrayList<>();
        for (FieldError fieldError : e.getBindingResult().getFieldErrors()) {
            messageList.add(fieldError.getDefaultMessage());
        }
        return Response.fail(HttpStatus.BAD_REQUEST.value(), String.join("&", messageList));
    }

    @ExceptionHandler({AbstractException.class})
    public ResponseEntity<Response<?>> handlerException(AbstractException e) {
        Integer code = e.code();
        Response<Void> response = Response.fail(code, e.getMessage());
        return new ResponseEntity<>(response, HttpStatus.valueOf(code));
    }

    @ExceptionHandler({RuntimeException.class})
    public ResponseEntity<Response<?>> handlerBaseException(RuntimeException e) {
        int code = HttpStatus.INTERNAL_SERVER_ERROR.value();
        Response<Void> response = Response.fail(code, e.getMessage());
        return new ResponseEntity<>(response, HttpStatus.valueOf(code));
    }
}
